//
//  HomeTableViewController.swift
//  微博个人swift
//
//  Created by 李灏 on 16/1/30.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class HomeTableViewController: BaseTableViewController {
    
    private var lastCount = 0
    //模型数组
    private lazy var statusListViewModel = StatusListViewModel()
    //cellId
    private let homeCell = "homeCell"
    //新微博数
    var badgeValue:Int = 0 {
        didSet {
            if self.badgeValue==0 {
                tabBarItem.badgeValue = nil
            }else{
            tabBarItem.badgeValue = "\(self.badgeValue)"
            }
        }
    }
    //下拉刷新控件
    let myRefrshControl = WBRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()
        //如果没有登录就不要设置tableView
        if !useLogrin {
            visitroLoginView?.setupUIWithInfo(nil, tipText: "关注一些人,回这里看看有什么惊喜")
            return
        }
        getRemind()
        prepareForTableView()
        loadData()
        let timer = NSTimer(timeInterval: 1, target: self, selector: "getRemind", userInfo: nil, repeats: true)
        let run = NSRunLoop.currentRunLoop()
        run.addTimer(timer, forMode: NSRunLoopCommonModes)
        print(self.badgeValue)
        
      
    }
    //获取未更新微博数
    func getRemind() {
        AccountViewModel.sharedAccountViewModel.getRemind { (badgeValue) -> () in
            self.badgeValue = badgeValue
        }
    }
    @objc private func loadData() {
        //使用视图模型来获取 网络请求的结果  -> 模型数组
        refreshControl?.beginRefreshing()
        statusListViewModel.loadHomeData(indicatorView.isAnimating()) { (isSuccess) -> () in
            self.refreshControl?.endRefreshing()
            //等待网络请求结束之后 修改控件的刷新状态
            self.myRefrshControl.endRefreshing()
            if isSuccess {
                if self.indicatorView.isAnimating() {
                    //上拉操作
                    //停止转动
                    self.indicatorView.stopAnimating()
                }else{
                    //下拉刷新的操作
                    //刷新成功的提示
                    self.showTipLabel()
                }
                //记录上一次模型数组中的数量
                self.lastCount = self.statusListViewModel.statues.count
                //请求数据成功
                self.tableView.reloadData()
            } else {
                //请求数据失败
                SVProgressHUD.showErrorWithStatus("网络君正在睡觉,请稍后再试")
            }
        }
    }
    //懒加载菊花
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    //注册tableView
    private func prepareForTableView() {
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: homeCell)
        //自动计算行高
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置分割线
        tableView.separatorStyle = .None
        //最简单的下拉刷新
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        //添加自定义下拉刷新控件
        self.tableView.addSubview(myRefrshControl)
        myRefrshControl.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        //将小菊花设置 为 tableFooterView
        tableView.tableFooterView = indicatorView
        
        tableView.scrollsToTop = true
        
        //添加提示的文案
        self.navigationController?.navigationBar.addSubview(tipLabel)
        //移动最下面
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    private func showTipLabel() {
        //记录数组上一次数据的数量
        let delta = self.statusListViewModel.statues.count - lastCount
        tipLabel.text = delta == 0 ? "没有新微博" : "有\(delta)条新微博"
        //记录初始位置
        let rect = tipLabel.frame
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.tipLabel.frame = CGRect(x: 0, y: 44, width: KWidth, height: 44)
            }) { (_) -> Void in
                //延迟动画
                UIView.animateKeyframesWithDuration(0.25, delay: 1, options: [], animations: { () -> Void in
                    //恢复初始位置
                    self.tipLabel.frame = rect
                    }, completion: { (_) -> Void in
                        print("OK")
                })
        }
    }
    //懒加载提示label
    private lazy var tipLabel:UILabel = {
        let lb = UILabel(frame: CGRect(x: 0, y: -64, width: KWidth, height: 44))
        lb.textColor = UIColor.whiteColor()
        lb.backgroundColor = UIColor.orangeColor()
        lb.textAlignment = .Center
        return lb
    }()

    
}
extension HomeTableViewController {
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statusListViewModel.statues.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(homeCell, forIndexPath: indexPath) as! StatusCell
        //如果正在加载最后一条cell  并且 小菊花没有转动的情况下 才去获取更多数据
        if indexPath.row == self.statusListViewModel.statues.count - 1 && !indicatorView.isAnimating(){
            //正在加载最后一条cell
            //加载数据
            //转动小菊花 等网络数据获取完毕之后再停止装懂即可
            indicatorView.startAnimating()
            loadData()
        }
        
        cell.status = statusListViewModel.statues[indexPath.row]
        
        return cell
    }
    

}
